const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('./logger')
const routers = require('./routes/routers')

// error handler
onerror(app)

// middlewares
app.use(bodyparser({
  enableTypes: ['json', 'form', 'text']
}))
app.use(json())
app.use(require('koa-static')(__dirname + '/public'))

app.use(views(__dirname + '/views', {
  extension: 'pug'
}))

/*
 * allow content type header
 * allow all origin request 
 */ 
app.use(async (ctx, next) => {
  ctx.set("Access-Control-Allow-Headers","content-type");
  if (ctx.request.header.origin !== ctx.origin) {
    ctx.set("Access-Control-Allow-Origin", "*");
  }
  await next();
})
/*
 * allow Options method ,and skip it
 */ 
app.use(async (ctx, next) => {
  if (ctx.method === "OPTIONS") {
    ctx.set('Access-Control-Allow-Methods', 'PUT,DELETE,POST,GET');
    ctx.set('Access-Control-Max-Age', 3600 * 24); // 这个响应头的意义在于，设置一个相对时间，在该非简单请求在服务器端通过检验的那一刻起，当流逝的时间的毫秒数不足Access-Control-Max-Age时，就不需要再进行预检，可以直接发送一次请求
    ctx.body = '';
  }
  await next();
})

// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  logger.info(`${ctx.method} ${ctx.url} - ${ms}ms`)
})

// routes
app.use(routers.routes(), routers.allowedMethods())

// error-handling
app.on('error', (err, ctx) => {
  logger.error('server error', err, ctx)
});

module.exports = app